package com.example.safeassistan.home.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.OverDueHiddenDangerDetail;
import com.example.safeassistan.home.adapter.CheckLogDetailFragmentAdapter;
import com.example.safeassistan.home.model.CheckLogDetailModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class CheckLogDetailFragment extends BaseVPFragment {
    private Context context;
    private View view;
    private CheckLogDetailFragmentAdapter adapter;
    private RecyclerView rcView;
    private SmartRefreshLayout refresh;
    private LinearLayout llNodata;
    private String recordTableId="";
    private List<CheckLogDetailModel.ResultDTO.RecordsDTO> data;
    private int currentPage=1;
    private int count=0;

    public static CheckLogDetailFragment newInstance(String  recordTableId) {
        Bundle arguments = new Bundle();
        arguments.putString("recordTableId",recordTableId);
        CheckLogDetailFragment fl = new CheckLogDetailFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.checklog_detail_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        recordTableId=getArguments().getString("recordTableId");
        rcView=view.findViewById(R.id.rcView);
        llNodata=view.findViewById(R.id.llNodata);
        refresh=view.findViewById(R.id.refresh);
        setView();
        getData();

    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) { }

    @Override
    protected void onFragmentFirstVisible() {

    }

    public void getData(){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("pageNo", String.valueOf(currentPage));
            jsonObject.put("pageSize",String.valueOf(PAGESIZE));
            jsonObject.put("recordTableId",recordTableId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.getCheckedRecordItemDetail, null,jsonObject ,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int  code = jsonObject.getInt("code");
                    if (code==200) {
                        Object obj = JsonUtils.fromJson(result.toString(), CheckLogDetailModel.class);
                        if (obj instanceof CheckLogDetailModel) {
                            CheckLogDetailModel  riskPointDetail=(CheckLogDetailModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = riskPointDetail.getResult().getTotal();
                                if (riskPointDetail.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=riskPointDetail.getResult().getRecords();
                                    adapter=new CheckLogDetailFragmentAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                @Override
                                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                    switch (view.getId()){
                                        case R.id.tvDetail:
                                            OverDueHiddenDangerDetail.actionStart(context,data.get(position).getDisposeStatus(),
                                                    1,data.get(position).getHiddenId()
                                                    ,Integer.parseInt(data.get(position).getRectSubmit()==null?"":data.get(position).getRectSubmit()));
                                            break;
                                    }
                                }
                            });
                                } else {
                                    llNodata.setVisibility(View.VISIBLE);
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            } else {
                                data.addAll(riskPointDetail.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishRefresh();
                refresh.finishLoadMore();
            }
        });
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }
}